import _ from "lodash";
import {type DataItem} from "../types/tool/dao.types";
import type {Condition, Orders} from "../types/tool/query.types";


export type QueryBean = {
    includes?: DataItem,
    excludes?: DataItem,
    orders?: Orders,
    page?: number,
    size?: number,
}


export class Query {
    condition: Condition;
    orders: Orders;
    page: number;
    size: number;
    template: DataItem;
    search: Condition[];

    constructor(
        queryBean: QueryBean,
    ) {
        this.condition = {
            includes: this.clearCondition(queryBean.includes),
            excludes: this.clearCondition(queryBean.excludes),
        }
        this.orders = queryBean.orders || {sort: -1};
        this.page = queryBean.page || 1;
        this.size = queryBean.size || 0;
        this.template = this.getTemplate()
        this.search = []
    }

    private clearCondition(cond: DataItem = {}) {
        const keys = Object.keys(cond).filter(key => cond[key] == null || cond[key] == '');
        return _.omit(cond, keys)
    }

    private getTemplate() {
        const includes = this.condition.includes;
        const keys = Object.keys(includes).filter(key => !key.includes('__'))
        return _.pick(includes, keys)
    }
}

